package com.luntan.action;

import java.io.ByteArrayInputStream;
import java.util.Map;

import com.luntan.domain.TUser;
import com.luntan.service.TUserService;
import com.luntan.util.web.Page;
import com.opensymphony.xwork2.ActionContext;

/**
 * 用户控制层
 * 
 * @author mashiqiong
 *
 */
public class TUserAction extends BaseAction {
	private Page<TUser> page = new Page<TUser>();
	private TUserService tUserService;
	private TUser tUser;
	private ByteArrayInputStream inputStream;
	private String code;

	/**
	 * 登录
	 *
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		TUser temp= this.tUserService.get(new TUser(tUser.getUserName()));
		if(temp==null){
			addFieldError("userName", "账号有误");
			return INPUT;
		}
		
		if(!temp.getPassword().equals(tUser.getPassword())){
			addFieldError("password", "密码有误");
			return INPUT;
		}
		
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("User", temp);
		return "listMainTie";
	}
	
	/**
	 * 验证登录信息是否合法
	 */
	public void validateLogin() {
		common();
	}

	private void common() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		String rand = (String) session.get("rand");
		
		if(code==null||"".equals(code)){
			addFieldError("code", "验证码不能为空");
		}
		
		if(!code.equals(rand)){
			addFieldError("code", "验证码不正确");
		}
		
		if(tUser.getUserName()==null||"".equals(tUser.getUserName())){
			addFieldError("userName", "用户名不能为空");
		}
		
		if(tUser.getPassword()==null||"".equals(tUser.getPassword())){
			addFieldError("password", "密码不能为空");
		}
	}
	
	/**
	 * 验证登录信息是否合法
	 */
	public void validateregiste() {
		common();
	}
	
	/**
	 * 注册会员
	 *
	 * @return
	 * @throws Exception
	 */
	public String registe() throws Exception {
		boolean flag= this.tUserService.addSave(tUser);
		if(!flag){
			addActionError("注册失败");
			return INPUT;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 列表
	 *
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		page = new Page<TUser>();
		page.setResultlist(this.tUserService.getList());

		return SUCCESS;
	}

	public Page<TUser> getPage() {
		return page;
	}

	public void setPage(Page<TUser> page) {
		this.page = page;
	}

	public TUser gettUser() {
		return tUser;
	}

	public void settUser(TUser tUser) {
		this.tUser = tUser;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void settUserService(TUserService tUserService) {
		this.tUserService = tUserService;
	}

	@Override
	public void setInputStream(ByteArrayInputStream inputStream) throws Exception {
		this.inputStream = inputStream;
	}
	
	@Override
	public ByteArrayInputStream getInputStream() throws Exception {
		return this.inputStream;
	}
}
